/**
 * @author {Yuntao Zhou}
 */
var RTQ_Forex_Ticker = function(config){
	this.lg = QS_Lang.forex;
    this.config=config||{};
    this.gKey=this.config.gKey;
    this.container=this.config.container;
    this.group=this.config.group||null;
    this.tickerDom={};
    this.el=null;
    this.HTML = '<div class="forex-ticker"><div class="forex-tk">' +
    '<div class="forex-tk-hd"><div class="symbol" gKey="'+this.gKey+'"></div>' +
    '<div class="operate"><div class="timer"></div>' +
    '<div class="close"></div></div></div>' +
    '<div class="forex-tk-bd">' +
    '<div class="lsh">' +
    '<div class="low"><div class="hd">'+this.lg["low"]+'</div><div class="bd"></div></div><div class="spread"><div class="hd">'+this.lg["spread"]+'</div><div class="bd spread-font"></div></div><div class="high"><div class="hd">'+this.lg["high"]+'</div><div class="bd"></div></div>' +
    '</div><div class="rate-bd">' +
    '<div class="rate"><div class="price"><div class="price-right"></div><div class="price-center"></div><div class="price-left"></div></div></div>' +
    '<div class="rate"><div class="price"><div class="price-right"></div><div class="price-center"></div><div class="price-left"></div></div></div>' +
    '</div>' +
    '</div></div><div class="tk-shadow"></div></div>';
    this.init();
};
RTQ_Forex_Ticker.prototype={
    init:function(){
        var self=this;
        this.el=$(this.HTML);
        this._initForexTickerDom();
        this.setTitle();
        this.initData();
        this.el.bind("click.ftk",function(e){
            var target=$(e.target); 
            if(target.hasClass("close")){
                if(self.group!=null){
                    var gKeyList=self.group.gKeyList;
                    var len=gKeyList.length;
                    var gKey=null;
                    self.group.unsubscribeSymbols([self.gKey]);
                    delete self.group.tkObjMaps[self.gKey];
                    for(var i=0;i<len;i++){
                        gKey=gKeyList[i];
                        if(gKey==self.gKey){
                            self.group.gKeyList.splice(i,1);
                            break;
                        }
                    }
                }           
                self.clear();
            }       
        });   
    },
    _initForexTickerDom:function(){     
        this.tickerDom = {
            symbolDom: this.el.find('.symbol')[0],
            timeDom: this.el.find('.timer')[0],
    //      lowDom: this.el.find('.low .bd')[0],
            spreadDom: this.el.find('.spread .bd')[0],
    //      highDom: this.el.find('.high .bd')[0],
            askDom:this.el.find('.rate')[1],
            askLeftDom: this.el.find('.rate .price-left')[1],
            askCenterDom: this.el.find('.rate .price-center')[1],
            askRightDom: this.el.find('.rate .price-right')[1],
            bidDom:this.el.find('.rate')[0],
            bidLeftDom: this.el.find('.rate .price-left')[0],
            bidCenterDom: this.el.find('.rate .price-center')[0],
            bidRightDom: this.el.find('.rate .price-right')[0]  
        };  
    },
    initData:function(){
        var nData=gData[this.gKey];
        if(!nData){
            return;
        }
        if(nData["Time"]){//if exist ,judge the oData  
            this.tickerDom.timeDom.innerHTML=FDate(nData["Time"]);  
        }else{
            this.tickerDom.timeDom.innerHTML='';    
        }       
//      if(nData["LowPrice"]){
//          this.tickerDom.lowDom.innerHTML=this.formatPrice(this.gKey,nData["LowPrice"]);
//      }else{
//          this.tickerDom.lowDom.innerHTML='';
//      }       
//      if(nData["HighPrice"]){
//          this.tickerDom.highDom.innerHTML=this.formatPrice(this.gKey,nData["HighPrice"]);
//      }else{
//          this.tickerDom.highDom.innerHTML='';
//      }       
        if(nData["AskPrice"]){
            var askPrice=this.formatPrice(this.gKey,nData["AskPrice"]);
            this.tickerDom.askLeftDom.innerHTML=this.splitPrice(this.gKey,askPrice)[0];
            this.tickerDom.askCenterDom.innerHTML=this.splitPrice(this.gKey,askPrice)[1];
            this.tickerDom.askRightDom.innerHTML=this.splitPrice(this.gKey,askPrice)[2];
        }else{
            this.tickerDom.askLeftDom.innerHTML='';
            this.tickerDom.askCenterDom.innerHTML='';
            this.tickerDom.askRightDom.innerHTML='';
        }
        if(nData["BidPrice"]){
            var bidPrice=this.formatPrice(this.gKey,nData["BidPrice"]);
            this.tickerDom.bidLeftDom.innerHTML=this.splitPrice(this.gKey,bidPrice)[0];
            this.tickerDom.bidCenterDom.innerHTML=this.splitPrice(this.gKey,bidPrice)[1];
            this.tickerDom.bidRightDom.innerHTML=this.splitPrice(this.gKey,bidPrice)[2];    
        }else{
            this.tickerDom.bidLeftDom.innerHTML='';
            this.tickerDom.bidCenterDom.innerHTML='';
            this.tickerDom.bidRightDom.innerHTML='';    
        }
        if(nData["BidPrice"]&&nData["AskPrice"]){
            this.tickerDom.spreadDom.innerHTML=this.formatPrice(this.gKey,Math.abs(this.formatPrice(this.gKey,nData["BidPrice"])-this.formatPrice(this.gKey,nData["AskPrice"])));
        }else{
            this.tickerDom.spreadDom.innerHTML='';
        }
    },
    updateData:function(gKey,oData){
        if(!oData){
            return false;
        }       
        var nData=gData[gKey];
        if(gKey==this.gKey){            
            if(oData["Time"]){//if exist ,judge the oData  
                this.tickerDom.timeDom.innerHTML=FDate(nData["Time"]);  
            }
//          if(oData["LowPrice"]){
//              this.tickerDom.lowDom.innerHTML=this.formatPrice(gKey,nData["LowPrice"]);
//          }
//          if(oData["HighPrice"]){
//              this.tickerDom.highDom.innerHTML=this.formatPrice(gKey,nData["HighPrice"]);
//          }           
            if(oData["AskPrice"]){
                var askPrice=this.formatPrice(gKey,nData["AskPrice"]);
                this.tickerDom.askLeftDom.innerHTML=this.splitPrice(gKey,askPrice)[0];
                this.tickerDom.askCenterDom.innerHTML=this.splitPrice(gKey,askPrice)[1];
                this.tickerDom.askRightDom.innerHTML=this.splitPrice(gKey,askPrice)[2];
                this.flash(this.tickerDom.askDom,nData["AskPrice"],oData["AskPrice"]["oValue"]);
            }
            if(oData["BidPrice"]){
                var bidPrice=this.formatPrice(gKey,nData["BidPrice"]);
                this.tickerDom.bidLeftDom.innerHTML=this.splitPrice(gKey,bidPrice)[0];
                this.tickerDom.bidCenterDom.innerHTML=this.splitPrice(gKey,bidPrice)[1];
                this.tickerDom.bidRightDom.innerHTML=this.splitPrice(gKey,bidPrice)[2];
                this.flash(this.tickerDom.bidDom,nData["BidPrice"],oData["BidPrice"]["oValue"]);
            }
            if(oData["BidPrice"]||oData["AskPrice"]){
                this.tickerDom.spreadDom.innerHTML=this.formatPrice(gKey,Math.abs(this.formatPrice(gKey,nData["BidPrice"])-this.formatPrice(gKey,nData["AskPrice"])));
            }
        }
    },
    flash:function(el,newVal,oldVal){//v:new value,c:old value
        var objEl=$(el);
        if(!oldVal || !newVal || objEl.length <1){
            return;
        }
        var priceRight=objEl.find('.price-right');  
        if (newVal >= oldVal) {
            if (!objEl.hasClass("rise")){
                objEl.removeClass('down').addClass('rise');
            }           
        }else{
            if (!objEl.hasClass("down")) {
                objEl.removeClass('rise').addClass('down');
            }
        }       
        if(newVal-oldVal>=0){
            if(!priceRight.hasClass('price-right-rise')){
                priceRight.removeClass('price-right-down').addClass('price-right-rise');
            }
        }else{
            if(!priceRight.hasClass('price-right-down')){
                priceRight.removeClass('price-right-rise').addClass('price-right-down');
            }
        }
        setTimeout(function(){
            objEl.removeClass('rise down');
        },300);
    },
    formatPrice:function(gKey,price){
        if(!price){
            return " ";
        }
        if(gKey.indexOf("JPY")>-1){
            return price.toFixed(3);
        }else{
            return price.toFixed(5);
        }
        return price;
    },  
    splitPrice:function(gKey,price){
        if(!price){
            return [" "," "," "];
        }
        var aPrices=[];
        price=price+'';
        var len=price.length;
        aPrices.push(price.substring(0, len - 3));
        aPrices.push(price.substring(len-3,len-1));
        aPrices.push(price.substring(len-1,len));
        return aPrices;
    },
    setTitle:function(t){
        if(t){
            this.tickerDom.symbolDom.innerHTML=t;
        }else{
            var t = this.gKey.split(":")[1];
            t =t.substring(0,3)+"/"+t.substring(3,6);
            this.tickerDom.symbolDom.innerHTML=t;
        }
    },
    getTitle:function(){
        return this.tickerDom.symbolDom.innerHTML;
    },
    setGKey:function(gKey){
        this.gKey=gKey;
    },
    getGKey:function(){
        return this.gKey;
    },
    clear:function(){
        this.el.unbind(".ftk");
        this.el.remove();
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    }
};

var RTQ_Forex=function(){
	this.lg = QS_Lang.forex;
    this.containerId = null;
    this.container = null;
    this.id = null;
    this.profile = null;
    this.el = null;
    this.pause = false;
    this.MianTickersData=null;
    this.width=null;
    this.height=null;
    this.tkScrollPN = null;
    this.settingMenu=null;
    this.viewTypeDDL=null;
    this._isInsertAtTop=false;
    this.viewStyle={txt:'Large',val:'large'};
    this.currentForexID=null;
    this.viewStyleDDL=null;
    this.tickers=[];
    this.gKeyList=[];
    this.tkObjMaps={};
    this.activeTickerEl=null;
    this.savedTitle = '';
    this.needRefeshForexList=true;
    this.maxListCount=10;// open forex max count
    this.cacheForexList = null;//forex list cache
    this.openMoreWindow = null;//workspaceManager.openOpenFileWin;
    this.hasSetting=null;
    this.dragable=null;
    this.HTML = '<div class="rtq-forex clearfix"><div class="forex-hd"><div class="forex-ddl"></div></div><div class="forex-bd"><ul class="forex-tk-menu"></ul></div></div>';   
};

RTQ_Forex.prototype={
    init:function(ContainerId,Profile,Sid){
        var self=this;
        this.containerId=ContainerId;
        this.container=$('#'+ContainerId);
        this.profile=Profile||{};
        this.id=Sid;
        this.el=$(this.HTML);
        this.el.appendTo(this.container);
        this.tkScrollPN = new Util.ScrollPanel(this.el.find('.forex-bd')[0], {
            showX: false
        });     
        this.MianTickersData=[{txt:'EUR/USD',val:'245:EURUSDFLIT'},
        {txt:'USD/JPY',val:'245:USDJPYFLIT'},
        {txt:'GBP/USD',val:'245:GBPUSDFLIT'},
        {txt:'EUR/CHF',val:'245:EURCHFFLIT'},
        {txt:'AUD/USD',val:'245:AUDUSDFLIT'},       
        {txt:'USD/CAD',val:'245:USDCADFLIT'},
        {txt:'EUR/GBP',val:'245:EURGBPFLIT'},
        {txt:'EUR/JPY',val:'245:EURJPYFLIT'},
        {txt:'GBP/JPY',val:'245:GBPJPYFLIT'},
        {txt:'CHF/JPY',val:'245:CHFJPYFLIT'},       
        {txt:'GBP/CHF',val:'245:GBPCHFFLIT'},
        {txt:'EUR/AUD',val:'245:EURAUDFLIT'},
        {txt:'EUR/CAD',val:'245:EURCADFLIT'},
        {txt:'EUR/SEK',val:'245:EURSEKFLIT'},
        {txt:'AUD/CAD',val:'245:AUDCADFLIT'},       
        {txt:'CAD/JPY',val:'245:CADJPYFLIT'},
        {txt:'NZD/JPY',val:'245:NZDJPYFLIT'},
        {txt:'GBP/AUD',val:'245:GBPAUDFLIT'},
        {txt:'AUD/NZD',val:'245:AUDNZDFLIT'},
        {txt:'EUR/NZD',val:'245:EURNZDFLIT'}];      
        if(this.setTitle&&Profile.title){
            this.setTitle(Profile.title);
        }           
        if(Profile.viewStyle){
            this.viewStyle=Profile.viewStyle;
        }    
        this.hasSetting=Profile.hasSetting===false?false:true;
        this.dragable=Profile.dragable===false?false:true;

        
        this.currentForexID=Profile.currentForexID?parseInt(Profile.currentForexID,10):0;
        if (this.hasSetting) {
            this.createSettingPn();
        }
        if(this.currentForexID<=0){
            if(Profile.tickers){
                this.tickers=Profile.tickers;
            }else{
                this._setDefaultTickers();
            }
            this._initOthers();
        }else{
            DBHelper.getWidgetTemplate(this.currentForexID,function(o){
                if (o != '') {
                    o = $.evalJSON(o);
                    self.tickers = o.tickers;
                    self.viewStyle = o.viewStyle;
                }         
                self._initOthers();
            });
        }
    }, 
    _enableDrag:function(tickerObj){
        var self = this;
        var drag=new Util.Dragable(tickerObj.el, {
            onDragStart: function(e, proxy){
                proxy.html("FROEX:"+tickerObj.getTitle());
                proxy._ticker = tickerObj.getGKey();
                proxy._cpnId = self.id;
                proxy._secType=20;
            }
        }, {
            autoProxy:true,
            delay:100,
            group:'gridDDGroup'
        });
    }, 
    _initOthers:function(){
        this.addTickers(this.tickers,false);
        this._setView(this.viewStyle);      
        this.changeOutSize(this.width,this.height);
        this._initActiveTickerEvent();
        this._initTickerMenu();
        this._initMianTickersDDL();
        if (this.viewTypeDDL != null) {
            this.viewTypeDDL.selectItemByValue(this.viewStyle.val);
        }
    },
    _initTickerMenu:function(){
        var self=this;
        var tkMenuData=this.MianTickersData;
        var len=tkMenuData.length;
        var val=null;
        var txt=null;
        this.menuEl=this.el.find('ul');
        for(var i=0;i<len;i++){
            val=tkMenuData[i]["val"];
            txt=tkMenuData[i]["txt"];
            this.menuEl.append('<li><a value="'+val+'" href="#">'+txt+'</a></li>')
        }       
        this.menuEl.click(function(e){
            if(e.target.tagName.toLowerCase()=='a'){
                var target=$(e.target);
                var symbolEl=self.activeTickerEl.find('.symbol');
                self._replaceTicker(symbolEl.attr("gKey"),target.attr('value'));
                self.menuEl.find('li a').removeClass('on');
                target.addClass('on');
                self.menuEl.hide();
                return false;
            }else{
                 self.menuEl.hide();
                 self.changOutSize();
            }
        });
    },
    _replaceTicker:function(oGKey,nGKey){
        if(this.tkObjMaps[nGKey]){
            Util.message(TEXT.ForexExistPair);
        }else{
            var len=this.gKeyList.length;
            var tkObj=this.tkObjMaps[oGKey];
            this.unsubscribeSymbols([oGKey]);
            tkObj.setGKey(nGKey);
            tkObj.setTitle();           
            tkObj.initData();
            this.subscribeSymbols([nGKey]);
            for(var i=0;i<len;i++){
                if(oGKey==this.gKeyList[i]){
                    this.gKeyList[i]=nGKey;
                    delete this.tkObjMaps[oGKey];
                    break;
                }
            }
            this.tkObjMaps[nGKey]=tkObj;
            this.activeTickerEl.find('.symbol').attr("gKey",nGKey);
        }
    },
    _initActiveTickerEvent:function(){
        var self=this;
        var gKey=null;
        this.el.bind('click.forex',function(e){
            var target=$(e.target);                     
            if(self.activeTickerEl!=null){
                self.activeTickerEl.removeClass('forex-on').find('.close').hide();
            }
            self.activeTickerEl = target.closest(".forex-ticker",self.el);  
            self.activeTickerEl.addClass('forex-on').find('.close').show();
            
            if(target.hasClass('symbol')&&self.menuEl.css('display')=='none'){
                var pp = target.offset();
                var ppRelate = self.menuEl.parent().offset();
                var ddlTop=self.tkScrollPN.scrollTop;
                self.menuEl.css({ left: pp.left - ppRelate.left + 'px', top: pp.top - ppRelate.top + target.outerHeight() +ddlTop+ 'px' });
                self.menuEl.show();                 
            }else{
                self.menuEl.hide(); 
            }
            self.changeOutSize(self.width,self.height);                       
        });
    },
    changeOutSize:function(w,h){
        var parent = this.el.parent().parent();
        w = w || parent.width();
        h = h || parent.height();
        this.width=w;
        this.height=h;
        this.el.css({
            width: w,
            height: h
        });
        this.el.find('.forex-bd').css({width:w,height:h-30});
        this.tkScrollPN.reSize(w, h - 30);
    },
    _setView:function(viewStyle){
        var v=viewStyle.val;
        var el=this.el.find('.forex-bd');
        if(v=="small"){
            if(!el.hasClass("small")){
                el.addClass("small");
            }
        }else{
            if (el.hasClass("small")) {
                el.removeClass("small");
            }
        }
    },
    _initMianTickersDDL:function(){
        var self=this;
        var mainTickersDDL=new Util.DropDownList(self.el.find('.forex-ddl')[0], function(t,v){
            if(self.tkObjMaps[v]){
                Util.message(TEXT.ForexExistPair);
            }else{
                self.addTickers([v],false);
            }           
        }, self.MianTickersData, {triggerByClick:true, width:120,disable:false,actionAtInit:false});
    },
    acceptTicker:function(ticker){
        if(ticker==null||ticker==''){
            return false;
        }
        ticker=gIdMap[ticker];
        if(!this.tkObjMaps[ticker]){
            this.addTickers([ticker],true);
        }else{
            Util.message(TEXT.ForexExistPair);
        }
    },
    addTickers:function(tickers,isInsertAtTop){
        //here maybe we need through the tickerValidation
        this._isInsertAtTop=isInsertAtTop;
        this._validationCallback(tickers);
    },
    _validationCallback:function(tickers){
        var len=tickers.length;
        var tkObj=null;
        var gKey=null;
        var contentEl=this.el.find('.forex-bd');
        for(var i=0;i<len;i++){
            gKey=tickers[i];
            tkObj=new RTQ_Forex_Ticker({
                gKey:gKey,
                group:this
            });
            if(this._isInsertAtTop){
                tkObj.el.prependTo(contentEl);
                this.gKeyList.unshift(gKey);
            }else{
                tkObj.el.appendTo(contentEl);
                this.gKeyList.push(gKey);
            }
            this.tkObjMaps[gKey]=tkObj;
            if (this.dragable) {
                this._enableDrag(tkObj);
            }
        }       
        this.subscribeSymbols(this.gKeyList);
        this.changeOutSize(this.width,this.height);
    },
    subscribeSymbols:function(gKeyList){
        if(gKeyList==null||gKeyList.length==0){
            return;
        }
        this.tValidation.checkTickers(gKeyList);
    },
    unsubscribeSymbols:function(gKeyList){
        var list = [];var ls ,gKey;
        if(gKeyList==null||gKeyList.length==0){
            return;
        }
        var len=gKeyList.length;
        for(var i=0;i<len;i++){
            gKey=gKeyList[i];
            ls = gKey.split(":");
            list.push({gkey:gKey,paraList:[{sourceType:"D",serviceName:245,itemName:"20"+push.subSeparator+ls[1]+push.subSeparator+"-1"}],isSubscribeLevelII:false,forexType:'20'});
        }   
        if(list.length>0){
            if (push && push.proxy) {
                push.proxy.batchUnsubscribe(list);
            }
        }
    },
    _setDefaultTickers:function(){
        this.tickers=['245:EURUSDFLIT','245:USDJPYFLIT','245:GBPUSDFLIT','245:EURCHFFLIT','245:AUDUSDFLIT'
                ,'245:USDCADFLIT','245:EURGBPFLIT','245:EURJPYFLIT','245:GBPJPYFLIT','245:CHFJPYFLIT'
                ,'245:GBPCHFFLIT','245:EURAUDFLIT','245:EURCADFLIT','245:EURSEKFLIT','245:AUDCADFLIT'
                ,'245:CADJPYFLIT','245:NZDJPYFLIT','245:GBPAUDFLIT','245:AUDNZDFLIT','245:EURNZDFLIT'
                ];
    },
    createSettingPn:function(){
        var self=this;
        var vData = [{txt:"Large",val:"large"},{txt:"Small",val:"small"}];
        var loadingStr = '<li class="loading">'+this.lg["loading"]+'...</li>';    
        var forexStr = '<li><ul class="actgroup clearfix"><li class="act1"><a href="#" cmd="save" class="menu">'+this.lg["save"]+'</a></li><li>|</li><li class="act1"><a href="#" cmd="saveas" class="menu">'+this.lg["saveas"]+'</a></li><li>|</li><li class="act1"><a href="#" cmd="del" class="menu">'+this.lg["delete"]+'</a></li></ul></li>';
        var wlsmTemplate = '<ul class="forex-settingpn" ><li class="hassubmenu"><a href="#" class="menu" >'+this.lg["openforex"]+'</a><ul class="submenu openlist">'+loadingStr+'</ul></li>'
                         + forexStr
                         + '<li class="topline"></li><li class="subtitle">'+this.lg["display"]+'</li><li class="customview clearfix"></li></ul>';
        this.settingMenu = $(wlsmTemplate);
        this.openMoreWindow = workspaceManager.openOpenFileWin;
        this.viewTypeDDL=new Util.DropDownList(self.settingMenu.find('.customview')[0], function(t,v){
            self.viewStyle={txt:t,val:v};
            self._setView(self.viewStyle);
            self.changeOutSize(self.width,self.height);
        }, vData, {triggerByClick:true, width:140,disable:false,actionAtInit:false});       
        this.settingMenu.find('li a.menu').click(function(e){
            if($(this).parent().hasClass('disable')){return false;}
            var cmd = $(this).attr('cmd');
             switch (cmd) {
                case 'save':{
                    self.saveForex(self.currentForexID,'11');
                }
                break;
                case 'saveas':{     
                    self.savedTitle = '';
                    self.insertForex('11');                 
                }
                break;
                case 'del':{
                    self.deleteForex(self.currentForexID);
                }
                break;
            }
            return false;
        });
        this.settingMenu.find('.hassubmenu').hover(
            function(e){
                //create open list
                var $menu = $(this).children('.submenu');
                if($menu.hasClass('openlist')){
                    self.buildList($menu);
                }
                $menu.css({
                    left: ($(this).offset().left+$(this).width()+$menu.width())>$('body').width()?-$menu.width():$(this).width()
                }).show();
            },
            function(e){
                $(this).children('.submenu').hide();
            }
        );  
        this.settingMenu.find('.openlist').click(function(e){
            if(e.target.tagName.toLowerCase() == 'a'){
                id = $(e.target).attr('cmd');
                if(id == -1){
                    self.openMoreWindow({'Forexlist':self.cacheForexList}, function(el){
                        self.openForex(el.getAttribute('cmd'), el.innerHTML,"11");
                        self.enableMenu();
                    });
                } else if(id != '') {
                    self.openForex(id, e.target.innerHTML,"11");
                    self.enableMenu();
                }
                $(this).hide();
                return false;
            }
        });
        if (this.viewTypeDDL != null) {
            this.viewTypeDDL.setTextValue(this.viewStyle.txt, this.viewStyle.val);
        }
        this.buildList();// get the saved forex list so that we can validate the title. 
    },  
    getSettingPanelDOM:function(){
        return settingPanelDOM = this.settingMenu[0];
    },
    openForex:function(id,el,type){
        var self=this;
        self.showLoading();
        self.setCurrentForexID(parseInt(id,10));
        DBHelper.getWidgetTemplate(id,function(o){
            o=$.evalJSON(o);
            var tickers=o.tickers;
            var viewStyle=o.viewStyle;
            var title=o.title;          
            self.reBindData(tickers,viewStyle);
            if (self.setTitle && title) {
                    self.setTitle(title);
            }
            self.savedTitle = name || self.getTitle();
            self.hideLoading();
        });
    },
    reBindData:function(tickers,viewStyle){
        this.clearTickers();
        this.viewStyle=viewStyle;
        this.addTickers(tickers,false);
        this._setView(viewStyle);
        
        if (this.viewTypeDDL != null) {
            this.viewTypeDDL.setTextValue(viewStyle.txt, viewStyle.val);
        }
    },
	_isExistName:function(name){
		if(this.cacheForexList==null){
			return false;
		}
		for(var i=0,l=this.cacheForexList.length;i<l;i++){
			if(name==this.cacheForexList[i].text){
				return true;
			}
		}
		return false;
	},
    saveForex:function(id,type,callback){
        var self=this;
        if(id==0){
            this.insertForex(type);
        }else{
            this.showLoading();
            DBHelper.saveWidgetTemplate(id, self.getProfile(), function(o){
                if(o=='-1'){
                    Util.message(TEXT.ForexSaveError);
                }else{
                    Util.message(TEXT.ForexSavedSuccessfully);
                }
            });
            self.hideLoading();
        }
    },
    insertForex:function(type,callback){
        var self=this;
        var doInsert=function(title){
            if (title.length < 1 || $.trim(title) == '') {
                Util.message(TEXT.ForexInput);
                self.insertForex(type, callback);
                return;
            }
            if (title.length > 20) {
                Util.message(TEXT.ForexTitle);
                self.insertForex(type, callback);
                return;
            }
            if (title=='Untitled') {
                Util.prompt(TEXT.ForexInput2, doInsert);
                return;
            }
            if (!QS_Validator.test(title, 'name')) {
                self.insertForex(type, callback);
                return;
            }
            if (self._isExistName(title)){
                Util.message(TEXT.ForexSameName);
                self.insertForex(type, callback);
                return;
            }
            
            self.showLoading();
            
            DBHelper.insertWidgetTemplate(type,self.getProfile(title),function(o){      
                if(o=='-1'){
                    Util.alert(TEXT.ForexSaveError);
                }else{
                    self.setTitle(title); 
                    self.setCurrentForexID(parseInt(o,10));
                    self.enableMenu(); 
                    self.needRefeshForexList = true;
                    self.buildList();
                    Util.message(TEXT.ForexSavedSuccessfully);    
                    self.savedTitle = title || self.getTitle();  
                }           
            });
            self.hideLoading();
        };
        if(self.savedTitle.length>0){
            doInsert(self.savedTitle);
        }else{
            Util.prompt(TEXT.ForexInput2,doInsert);
        }
    },
    deleteForex:function(id,callback){
        var self=this;
        if(id<0){
            return;
        }
        Util.confirm(TEXT.ForexDelConfirm, function(b){
            if (!b) {
                return;
            }
            DBHelper.deleteWidgetTemplate(id,function(o){
                self.setCurrentForexID(0);
                self.needRefeshForexList = true;
                self.buildList();
                self.clearTickers();
				self._setDefaultTickers();
				self.addTickers(self.tickers,false);
                if (self.setTitle) {
                    self.setTitle('Forex Dealing');
                    self.savedTitle='Forex Dealing';
                }
                self.changeOutSize(self.width,self.height);
            });
        });
    },
    getProfile:function(title){
        return {
            tickers:this.gKeyList,
            viewStyle:this.viewStyle,
            title:title||this.getTitle()
        };
    },
    setCurrentForexID:function(id){
        this.currentForexID=id;
    },
    enableMenu:function(){
        this.settingMenu.find('li.act1').removeClass('disable');
    },
    buildList:function($list){
        var self=this;
        $list = $list||this.settingMenu.find('.openlist');
        if(this.needRefeshForexList){
            DBHelper.getWidgetTemplateListByType("11",function(o){
                var str =  '';
                if (!o || o == '') {
                    str += '<li class="nofile">'+self.lg["nofile"]+'</li>';            
                    self.needRefeshForexList = true;
                }else{
                    var lst = $.evalJSON(o).temp || [];
                    if (!lst || lst.length < 1) {
                        str += '<li class="nofile">'+self.lg["nofile"]+'</li>';
                    }else{
                        var len = lst.length < self.maxListCount ? lst.length : self.maxListCount;
                        var flc = [];
                        self.cacheForexList = [];
                        str += '<li class="line">Forexs</li>';
                        for(var i=0;i<lst.length;i++){
                            if(flc.length<len){
                                flc.push(lst[i]);
                            } 
                            self.cacheForexList.push({
                                text: lst[i].title,
                                cmd: lst[i].id
                            });
                        }
                        for (var i = 0; i < flc.length; i++) {
                            str += '<li><a href="#" cmd="' + flc[i].id + '" class="wl" >' + flc[i].title + '</a></li>';
                        }
                        str += '<li><a href="#" cmd="-1" class="more" >'+self.lg["more"]+'...</a></li>';
                        self.needRefeshForexList = false;
                    }
                }
                self.settingMenu.find('.openlist').empty().html(str);
            });
        }
    },
    clearTickers:function(){
        this.unsubscribeSymbols(this.gKeyList);
        for(var o in this.tkObjMaps){
            this.tkObjMaps[o].clear();
        }
        this.tkObjMaps={};
        this.gKeyList=[];
        this.tickers=[];
    },
    clear:function(){
        this.clearTickers();
        this.el.unbind(".forex");
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    },  
    updateData:function(gKey,oData){
        if (this.tkObjMaps[gKey]) {
            this.tkObjMaps[gKey].updateData(gKey, oData);
        }
    },
    saveConfig:function(){      
        return {
            tickers: this.gKeyList,
            title: this.getTitle(),
            currentForexID:this.currentForexID,
            viewStyle:this.viewStyle
        };
    },
    setViewStyle:function(val){
       if(val=='large'){
           this._setView({
              txt:this.lg["large"],
              val:'large'
           });
       }else if(val=='small'){
           this._setView({
              txt:this.lg["small"],
              val:'small'
           });
       }    
    },
    acceptTickers:function(tickers,isTop){
       if(tickers==''){
           return;
       }
       isTop=isTop===true?true:false;       
       var tk,tks=[],tickerList=tickers.split(","),flag=false;
       for(var i=0,l=tickerList.length;i<l;i++){
           tk="245:"+tickerList[i]+"FLIT";
           for(var j=0,len=this.MianTickersData.length;i<l;i++){
              if(tk==this.MianTickersData[i].val){
                  flag=true;
                  tks.push(tk);
                  break;
              }
           }
       }
       this.addTickers(tks,isTop);
    }
};



